package cn.yunpeixue.jvm.controller.lock;

import cn.yunpeixue.jvm.common.JResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = "线程锁demo演示", value = "线程锁demo演示")
@RestController
public class LockController {
   private Object o = new Object();
   private Object k = new Object();

    /**
     *  演示锁demo
     * @return
     */
    @GetMapping("/lock/locked")
    @ApiOperation(value = "演示锁demo")
    public JResult enscript(){
        Thread t1 = new Thread(this::m);
        t1.start();
        Thread t2 = new Thread(this::n);
        t2.start();
        return JResult.build().ok(1);
    }




    void m() {
        String p = Thread.currentThread().getName();
        System.out.println("启动等待" + p);
        synchronized (o) {
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            synchronized (k) {

            }
            System.out.println("线程结束" + p);
        }
    }

    void n() {
        String p = Thread.currentThread().getName();
        System.out.println("启动等待" + p);
        synchronized (k) {
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            synchronized (o) {

            }
        }
        System.out.println("线程结束" + p);
    }


}
